package com.ruoyi.demo.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.demo.config.WechatConfiguration;
import com.ruoyi.demo.service.IAuctionUserService;
import com.ruoyi.demo.service.ITWxUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 微信用户服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TWxUserServiceImpl implements ITWxUserService {

    private static final int MAX_RETRY_COUNT = 3;
    private static final long RETRY_DELAY = 1000L; // 1秒
    private final IAuctionUserService auctionUserService;
    private final WechatConfiguration wxConfig;

    @Override
    public String getOpenid(String code) {
        try {
            String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                    wxConfig.getMiniapp().getAppid(),
                    wxConfig.getMiniapp().getSecret(),
                    code);

            String result = HttpUtils.sendGet(url);
            log.info("获取openid, url={}, result={}", url, result);

            if (StringUtils.isEmpty(result)) {
                throw new ServiceException("获取openid失败");
            }

            JSONObject jsonObject = JSON.parseObject(result);
            String openid = jsonObject.getString("openid");
            if (StringUtils.isEmpty(openid)) {
                String errmsg = jsonObject.getString("errmsg");
                log.error("获取openid失败: {}", errmsg);
                throw new ServiceException("获取openid失败: " + errmsg);
            }

            return openid;
        } catch (Exception e) {
            log.error("获取openid异常", e);
            throw new ServiceException("获取openid失败");
        }
    }

}
